package framework.core
{
import core.StageProxy;

import flash.display.DisplayObject;
import flash.display.InteractiveObject;
import flash.display.Stage;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;

import framework.view.components.Component;
import framework.view.components.tip.ITip;

import view.component.tip.CommonTip;

/**
 * TipManager
 * @author jliang
 *
 */
public class TipManager
{
	private static var MARGIN_X:Number = 18;
	
	private static var MARGIN_Y:Number = 0;
	
	private static var tipTrigger:InteractiveObject;
	
	private static var tip:ITip;
	
	private static function get defaultTipClassRef():Class
	{
		return CommonTip;
	}
	
	private static function get stage():Stage
	{
		return StageProxy.stage;
	}
	
	private static function get screenWidth():Number
	{
		return StageProxy.screenWidth;
	}
	
	private static function get screenHeight():Number
	{
		return StageProxy.screenHeight;
	}
	
	public static function showTip(trigger:InteractiveObject, data:*, ref:Class = null):void
	{
		removeTip();
		
		tipTrigger = trigger;
		
		tip = ComponentBuilder.create(ref ? ref : defaultTipClassRef);
		
		tip.data = data;
		
		trigger.addEventListener(Event.REMOVED_FROM_STAGE, removeHandler, false, 5);
		trigger.addEventListener(MouseEvent.MOUSE_OUT, onMouseOutHandler);
		trigger.addEventListener(Event.ENTER_FRAME, renderPosition);
		
		renderPosition(null);
		
		stage.addChild(tip as DisplayObject);
	}
	
	public static function removeTip():void
	{
		if (tipTrigger)
		{
			tipTrigger.removeEventListener(Event.REMOVED_FROM_STAGE, removeHandler);
			tipTrigger.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOutHandler);
			tipTrigger.removeEventListener(Event.ENTER_FRAME, renderPosition);
			tipTrigger = null;
		}
		
		if (tip)
		{
			if (tip.parent)
			{
				tip.parent.removeChild(tip as DisplayObject);
			}
			if (tip is Component)
			{
				Component(tip).dispose();
			}
			
			tip = null;
		}
	}
	
	private static function renderPosition(event:Event):void
	{
		if (!tip) return;
		
		var x:Number = stage.mouseX + MARGIN_X;
		
		if (tip.width + x >= screenWidth)
		{
			x = stage.mouseX - tip.width - MARGIN_X;
		}
		
		var y:Number = stage.mouseY + MARGIN_Y;
		
		if (tip.width + y >= screenHeight)
		{
			y = stage.mouseY - tip.height - MARGIN_Y;
		}
		
		tip.x = x;
		tip.y = y;
	}
	
	private static function onMouseOutHandler(event:Event):void
	{		
		removeTip();
	}
	
	private static function removeHandler(event:Event):void
	{
		removeTip();
	}
}
}


